package edu.qichen.onlineBlog.framework;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import edu.qichen.onlineBlog.framework.exception.BusinessException;
import edu.qichen.onlineBlog.framework.exception.ErrorCodeEnum;
import edu.qichen.onlineBlog.framework.utils.RedisUtils;
import edu.qichen.onlineBlog.user.pojo.User;
import edu.qichen.onlineBlog.user.mapper.UserMapper;
import edu.qichen.onlineBlog.user.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 功能:JWT生成token
 * 作者:程序员欧阳子韩
 * 日期:2024/4/6 17:31
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 重写HandlerInterceptor中preHandle()方法
     * 获取前端请求头中传来的token参数
     * 通过hutool进行对token验证是否为空
     * 拿到前端加密过的数据得到userId
     * 通过userId查找数据库，拿到对应userId的密码
     * 对密码进行加密生成token当作一个验证器
     *
     * @param request  -
     * @param response -
     * @param handler  -
     * @return -
     * @throws Exception -
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token"); // 获取请求头穿过来的参数
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");  // 如果没有在请求头中找到，尝试从URL参数中获取
        }

        // 如果不是映射到方法直接通过
        if (handler instanceof HandlerMethod) {
            AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if (annotation != null) {
                return true;
            }
        }

        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw BusinessException.build(ErrorCodeEnum.AUTH_ERROR);
        }

        //提取 token 中的 user id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0); // JWT.decode(token) 解码 jwt token
        } catch (JWTDecodeException j) {
            throw BusinessException.build(ErrorCodeEnum.AUTH_ERROR);
        }

        // 验证token是否有效（包括检查用户是否存在，以及token是否为用户的最新token）
        User user = userService.validateTokenAndGetUser(userId, token);

        // 通过用户密码加密之后生成一个验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            throw BusinessException.build(ErrorCodeEnum.AUTH_ERROR);
        }
        return true;
    }
}
